package com.ai_daily.aitiantian.api

import com.ai_daily.aitiantian.BuildConfig
import com.ai_daily.aitiantian.api.converter.CustomConverterFactory
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

/**
 * API 请求控制器
 */
class ApiClient {

    companion object {
        // 切换 Base Url
        private fun getBaseUrl(): String {
            val baseUrl = if (BuildConfig.DEBUG) {
                BaseUrls.getTestBaseUrl()
//                when(MMKVUtil.instance.decode(Constants.SP_SERVER_URL_KEY,ServerEnvironment.TEST)) {
//                    ServerEnvironment.TEST -> BaseUrls.getTestBaseUrl()
//                    ServerEnvironment.RELEASE -> BaseUrls.getBaseUrl()
//                    ServerEnvironment.CUSTOM -> ""
//                    else -> BaseUrls.getTestBaseUrl()
//                }
            } else {
                BaseUrls.getBaseUrl()
            }
            return baseUrl;
        }

        private var mRetrofit: Retrofit = provideRetrofit(getBaseUrl())
//            provideRetrofit(BaseUrls.getBaseUrl())

        private fun provideRetrofit(baseUrl: String): Retrofit {
            return Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(OkHttpModule().provideOkHttp())
//                 .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .addConverterFactory(CustomConverterFactory.create())
                .build()
        }
    }

    fun service(): ApiService = mRetrofit.create(ApiService::class.java)
    fun downloadService(startPoint: Long, listener: IDownloadListener): DownloadService {
        val retrofit = Retrofit.Builder()
            .baseUrl(BaseUrls.getBaseUrl())
            .client(OkHttpModule().provideDownOkHttp(startPoint, listener))
            // .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        return retrofit.create(DownloadService::class.java)
    }

}